var language = 'zh';

/* 1. Google translate uses JSONP to pass result to client site scripts;
 * 2. Custom strokes are evaluated in content scripts;
 * 3. Chrome isolates client site scripts from content scripts.
 * For above reasons, custom strokes can not get result from Google Translate
 * directly, because the callback function Google Translate can call, is in
 * client site scripts universe.
 * However, content script can access DOM objects and set some event handler
 * functions, we have to use one of such handlers as the carrier of our
 * translation result processor.
 * We should choose an unused handler;
 * We should not remember the handler.
 */
var carriers = [
	'onload',
	'onunload',
	'ondblclick',
	'onkeypress',
	'onkeyup',
	'onclick',
	'onmouseup'
];

var text = encodeURIComponent(_env.seltext),
	node = document.body,	/* It's always there */
	node_name = 'document.body',
	carrier, carrier_qualifier,
	shout = function(msg) { alert(msg) };

for (var i = 0; i < carriers.length; ++i) {
	if (!node[carriers[i]]) {
		carrier = carriers[i];
		carrier_qualifier = node_name + '.' + carriers[i];
		console.log('Use carrier: %s', carrier_qualifier);
		break;
	}
}

if (!carrier) {
	shout('Sorry, the web page you are currently browsing is too bloated, I do not want to translate anything on this page');
	return;
}

/* This function will be called in the client site script universe */
node[carrier] = function(resp) {
	var text = resp && resp.responseData && resp.responseData.translatedText	/* success */
		|| resp && resp.responseDetails;					/* failure */
	if (text) {
		shout(text);
	}
	/* self destruction, must set to null (set to undefined will create problems, don't know why) */
	eval('{' + carrier_qualifier + ' = null}');
}

/* Ask Google to translate for us */
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.google.com/uds/Gtranslate?v=1.0&callback=' + carrier_qualifier + '&langpair=|' + language + '&q=' + text;
document.getElementsByTagName('head')[0].appendChild(script);
